package com.study.shengsiyuan.example09;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class _1_NIOTest12 {
	public static void main(String[] args) throws IOException {
		int[] ports = new int[] {5000,5001,5002,5003,5004};
		Selector selector = Selector.open();
//		System.out.println(SelectorProvider.provider().getClass());

		for(int i=0;i<ports.length;i++) {
			ServerSocketChannel ssc = ServerSocketChannel.open();
			ssc.configureBlocking(false);
			ServerSocket ss =ssc.socket();
			ss.bind(new InetSocketAddress(ports[i]));
			ssc.register(selector, SelectionKey.OP_ACCEPT);
			System.out.println("监听端口 ： "+ ports[i]);
		}
		while(true) {
			int num = selector.select();
			System.out.println("num : "+ num);
			Set<SelectionKey>  sk = selector.selectedKeys();
			System.out.println("SelectionKey : " + sk) ;
			Iterator<SelectionKey> it = sk.iterator();
			while(it.hasNext()) {
				SelectionKey selectionKey= it.next();
				if(selectionKey.isAcceptable()) {
					ServerSocketChannel serverSocketChannel = (ServerSocketChannel)selectionKey.channel();
					SocketChannel socketChannel = serverSocketChannel.accept();
					socketChannel.configureBlocking(false);
					socketChannel.register(selector, SelectionKey.OP_READ);
					it.remove();
					System.out.println("获取到客户端连接 ： " + socketChannel);
				}else if (selectionKey.isReadable()) {
					SocketChannel socketChannel = (SocketChannel)selectionKey.channel();
					int br = 0;
					ByteBuffer  bb = ByteBuffer.allocate(1024) ;
					while((br = socketChannel.read(bb))!=-1) {
						bb.flip();
						socketChannel.write(bb);
						bb.clear();
					}
					System.out.println("读取 ： "+ br +" , 来自于 "+ socketChannel);
					it.remove();
				}
			}
		}
	}
}
